//
//  LockListViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 31/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import PKHUD
import CoreBluetooth

class LockListViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    fileprivate var locks: [WNLockModel] = [] {
        didSet {
            var model = WNLockModel()
            model.id = 3
            model.battery = 80
            model.mac = "FF:FF:F4:A4:7A:EE"
            model.memberGroup = 0
            model.state = 0
            model.name = "家大门"
            locks = [model]
            if locks.count > 0 {
                bleM.startScan()
                self.collectionView.reloadData()
            } else {
                showEmptyView(message: "暂未绑定锁，请先添加新锁")
            }
        }
    }
    fileprivate var devices: [String: BleDevice] = [:]
    
    private var bleM: BLEFacade! = {
        let config = BLEConfigure(serviceUUID: CBUUID(string: "FFF0"), readUUID: CBUUID(string: "FFF7"), writeUUID: CBUUID(string: "FFF6"))
        let bleM = BLEFacade(configure: config)
        return bleM
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotificationAddNewLockEvent(_:)), name: NSNotification.Name.WNLockAddNew, object: nil)
        doInitialization()
        fetchData()
        handlePasteboard()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    private func doInitialization() {
        confiureNavigationBar()
//        configureNavigationBarBack()
        self.navigationItem.title = "悟牛智锁"
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("添加新锁", for: .normal)
        rightBtn.titleLabel?.font = Fonts.regular(ofSize: 15)
        rightBtn.sizeToFit()
        rightBtn.setTitleColor(Colors.title, for: .normal)
        rightBtn.addTarget(self, action: #selector(handleAddNewLockEvent(_:)), for: .touchUpInside)
        let rightbtn = UIBarButtonItem(customView: rightBtn)
        navigationItem.rightBarButtonItem = rightbtn
        // ==== collection view
        collectionView.register(UINib(nibName: "WNLockCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "WNLockCell")
        //ble
        bleM.delegate = self
    }
    
    private func fetchData() {
        WNLockApi.lockList.execute { (result: FxResponseResult<[WNLockModel]>) in
            switch result {
            case .success(let locks):
                self.locks = locks
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    
    @objc private func handleAddNewLockEvent(_ sender: UIButton) {
        performSegue(withIdentifier: "pushToLockListViewController", sender: sender)
    }
    
    @objc private func handleNotificationAddNewLockEvent(_ sender: NSNotification) {
        fetchData()
    }

    // 判断是否有粘贴板
    private func handlePasteboard() {
        let pasteboard = UIPasteboard.general
        if let content = pasteboard.string, content.contains("【吾家智锁】"){
            let pattern = "(\\d{6})|(#tempKey=\\d{1,}#)"
            if let regular = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) {
                let matchs = regular.matches(in: content, options: .reportProgress, range: NSMakeRange(0, content.count))
                var results: [String] = []
                for match in matchs {
                    let result = (content as NSString).substring(with: match.range)
                    results.append(result)
                }
                print(results)
                if results.count >= 2 {
                    let tempKey = results[0]
                    let tempKeyStr = results[1].replacingOccurrences(of: "#", with: "")
                    let tempKeyId = Int(tempKeyStr.components(separatedBy: "=").last ?? "0")
                    let vc = UIStoryboard(name: "WNLockUI", bundle: nil).instantiateViewController(withIdentifier: "TempSecretKeyViewController") as! TempSecretKeyViewController
                    vc.tempKeyCode = Int(tempKey) ?? 0
                    vc.tempKeyId = tempKeyId ?? 0
                    navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
        //清空粘贴板
        pasteboard.string = ""
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segue.destination {
        case let vc as LockQRCodeViewController:
            if let cell = sender as? WNLockCollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
                vc.lock = locks[indexPath.row]
            }
        case let vc as MemberListViewController:
            if let cell = sender as? WNLockCollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
                vc.lock = locks[indexPath.row]
            }
        case let vc as LockEventsViewController:
            if let cell = sender as? WNLockCollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
                vc.lockId = locks[indexPath.row].id
            }
        case let vc as TempSecretKeyViewController:
            if let cell = sender as? WNLockCollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
                vc.lock = locks[indexPath.row]
            }
        default:
            break
        }
    }
    

}


// MARK: - UICollectionViewDataSource
extension LockListViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return locks.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let lock = locks[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WNLockCell", for: indexPath) as! WNLockCollectionViewCell
        cell.delegate = self
        cell.batteryLabel.text = "电量：\(lock.battery ?? 0)%"
        cell.nameLabel.text = lock.name
        cell.macAddrLabel.text = lock.mac
        var roleStr: String = ""
        switch lock.memberGroup {
        case 0?:
            roleStr = "管理员"
        case 1?:
            roleStr = "家庭成员"
        case 2?:
            roleStr = "保媒"
        case 3?:
            roleStr = "钟点工"
        default:
            roleStr = ""
        }
        cell.memberRoleLabel.text = roleStr
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension LockListViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let lock = locks[indexPath.row]
        let currentDevices = self.devices
        var currentDeivce: BleDevice?
        if let mac = lock.mac {
            let keyName = "WSL_" + mac[mac.index(mac.startIndex, offsetBy: 9) ..< mac.endIndex].replacingOccurrences(of: ":", with: "_")
            currentDeivce = currentDevices[keyName]
        }
        if let _ = currentDeivce {
            let lockCell = cell as! WNLockCollectionViewCell
            lockCell.bleStatusButton.isSelected = true
            lockCell.bleStatusLabel.text = "点击开锁"
        } else {
            let lockCell = cell as! WNLockCollectionViewCell
            lockCell.bleStatusButton.isSelected = false
            lockCell.bleStatusLabel.text = "不在附近"
        }
        
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
extension LockListViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
    }
}

// MARK: - WNLockCollectionViewCellDelegate
extension LockListViewController: WNLockCollectionViewCellDelegate {
    func wnLockCollectionViewCellClickForQrCode(cell: WNLockCollectionViewCell) {
        performSegue(withIdentifier: "pushToLockQRCodeViewController", sender: cell)
    }
    func wnLockCollectionViewCellClickForTempkey(cell: WNLockCollectionViewCell) {
        performSegue(withIdentifier: "pushToTempSecretKeyViewController", sender: cell)
    }
    func wnLockCollectionViewCellClickForAuthUsers(cell: WNLockCollectionViewCell) {
        performSegue(withIdentifier: "pushToMemberListViewController", sender: cell)
    }
    func wnLockCollectionViewCellClickForOpenRecord(cell: WNLockCollectionViewCell) {
        performSegue(withIdentifier: "pushToLockEventsViewController", sender: cell)
    }
    func wnLockCollectionViewCellClickForSetting(cell: WNLockCollectionViewCell) {
        if let indexPath = collectionView.indexPath(for: cell) {
            let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            let lock = locks[indexPath.row]
            switch lock.memberGroup {
            case 0?:
                // 重置蓝牙解锁
                let resetAction = UIAlertAction(title: "重置蓝牙解锁", style: .default) { _ in
                    self.resetLock(lock: lock)
                }
                alertController.addAction(resetAction)
                //停用/启用蓝牙解锁
                let startAction = UIAlertAction(title: (lock.state ?? 0) == 0 ? "启用蓝牙解锁" : "停用蓝牙解锁", style: .default) { _ in
                    self.startupLockOrNo(lock: lock)
                }
                alertController.addAction(startAction)
            default:
                break
            }
            // 删除门锁
            let deleteAction = UIAlertAction(title: "删除门锁", style: .default) { _ in
                self.deleteLock(lock: lock)
            }
            alertController.addAction(deleteAction)
            // 查看数字密码
            let checkSecretAction = UIAlertAction(title: "查看数字密码", style: .default) { _ in
                self.checkSecret(withLock: lock)
            }
            alertController.addAction(checkSecretAction)
            //取消
            alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            present(alertController, animated: true, completion: nil)
        }
        
    }
    func wnLockCollectionViewCellClickForOpeningLock(cell: WNLockCollectionViewCell) {
        if cell.bleStatusButton.isSelected {
            if let indexPath = collectionView.indexPath(for: cell) {
                let lock = locks[indexPath.row]
                var currentDevice: BleDevice?
                if let mac = lock.mac {
                    let keyName = "WSL_" + mac[mac.index(mac.startIndex, offsetBy: 9) ..< mac.endIndex].replacingOccurrences(of: ":", with: "_")
                    currentDevice = devices[keyName]
                }
                if let device = currentDevice {
                    // 获取basecode
                    WNLockApi.lockBasecode(lockId: lock.id, tempKeyId: nil).execute { result in
                        switch result {
                        case .success(let json):
                            let basecode = json["baseCode"].uInt32Value
                            let networkState = json["networkState"].intValue
                            if networkState == 200 {
                                // 网关在线
                            }
                            self.bleM.openLock(device: device, basecode: basecode, handler: { (info, error) in
                                if let e = error {
                                    HUD.flash(.label(e.domain), delay: 1.5)
                                }
                                if let code = info["code"] as? UInt8 {
                                    if code == 0 {
                                        HUD.flash(.label("开锁失败,请检查锁是否已断开"), delay: 1.5)
                                    }
                                }
                            })
                        case .failure(let error):
                            HUD.flash(.label(error.errMsg), delay: 1.5)
                        }
                    }
                    
                }
            }
            
        }
    }
}

// MARK: - 锁相关操作
extension LockListViewController {
    // 重置
    func resetLock(lock: WNLockModel) {
       //获取managerId
        WNLockApi.lockManager(lockId: lock.id ?? 0).execute { result in
            switch result {
            case .success(let json):
                let managerId = json["managerId"].uInt32Value
                let baseCode = json["baseCode"].uInt32Value
                self.resetLockStep1(lock: lock, basecode: baseCode, openId: managerId)
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    //启用
    func startupLockOrNo(lock: WNLockModel) {
        switch lock.state {
        case 0?://未启用
            WNLockApi.activeLock(lockId: lock.id ?? 0).execute { result in
                switch result {
                case .success:
                    self.fetchData()
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
        case 1?:
            WNLockApi.unbindLock(lockId: lock.id ?? 0).execute { result in
                switch result {
                case .success:
                    self.fetchData()
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
        default:
            break
        }
    }
    //删除
    func deleteLock(lock: WNLockModel) {
        WNLockApi.deleteLock(lockId: lock.id ?? 0).execute { result in
            switch result {
            case .success:
                self.fetchData()
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    //查看开锁密码
    func checkSecret(withLock lock: WNLockModel) {
        WNLockApi.setMyPwd(lockId: lock.id ?? 0).execute { result in
            switch result {
            case .success(let json):
                let password = json["password"].stringValue
                let alertController = UIAlertController(title: "密码锁开锁密码", message: "\(password)", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
                self.present(alertController, animated: true, completion: nil)
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
}

// MARK: - 重置锁
extension LockListViewController {
    func resetLockStep1(lock: WNLockModel, basecode: UInt32, openId: UInt32) {
        // 硬件解绑
        var currentDevice: BleDevice?
        if let mac = lock.mac {
            let keyName = "WSL_" + mac[mac.index(mac.startIndex, offsetBy: 9) ..< mac.endIndex].replacingOccurrences(of: ":", with: "_")
            currentDevice = devices[keyName]
        }
       
        if let device = currentDevice {
            bleM.unbindLock(device: device, openId: openId, basecode: basecode) {[weak self] (info, error) in
                if let e = error {
                    HUD.flash(.label(e.domain), delay: 1.5)
                } else {
                    self?.resetLockStep2(lock: lock, device: device, openId: openId)
                }
            }
        } else {
            HUD.flash(.label("该锁不在附近"), delay: 1.5)
        }
    }
    func resetLockStep2(lock: WNLockModel, device: BleDevice, openId: UInt32) {
        let basecode = UInt32.randomPrime(length: 8)
        bleM.bindLock(device: device, basecode: basecode, openId: openId) { [weak self](info, error) in
            if let e = error {
                HUD.flash(.label(e.domain), delay: 1.5)
            } else {
                self?.resetLockStep3(lock: lock, basecode: basecode)
            }
        }
    }
    func resetLockStep3(lock: WNLockModel, basecode: UInt32) {
        WNLockApi.resetLock(lockId: lock.id ?? 0, baseCode: Int(basecode)).execute { result in
            switch result {
            case .success:
                HUD.flash(.label("更新成功"), delay: 1.5)
                self.fetchData()
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
}
// MARK: - BLELockDelegate
extension LockListViewController: BLELockDelegate {
    func didDiscoverDevice(_ device: BleDevice) {
        if let name = device.name, name.contains("WSL_") {
            if let cell = collectionView.visibleCells.first as? WNLockCollectionViewCell, let indexPath = collectionView.indexPath(for: cell) {
                let lock = locks[indexPath.row]
                var currentDevice: BleDevice?
                if let mac = lock.mac {
                    let keyName = "WSL_" + mac[mac.index(mac.startIndex, offsetBy: 9) ..< mac.endIndex].replacingOccurrences(of: ":", with: "_")
                    currentDevice = devices[keyName]
                }
                if let _ = currentDevice {
                    cell.bleStatusButton.isSelected = true
                    cell.bleStatusLabel.text = "点击开锁"
                }
            }
            devices[name] = device
        }
    }
    func didUpdateState(_ state: CBCentralManagerState) {
        if state == .poweredOff {
            HUD.flash(.label("未打开蓝牙"), delay: 1.5)
        } else {
            bleM.startScan()
        }
    }
}
